<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="filter-container">
        <el-input
          v-model="listQuery.keyword"
          placeholder="请输入关键字"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter="handleFilter"
        />
        <el-button class="filter-item" type="primary" icon="Search" @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" type="primary" icon="Plus" @click="handleCreate">
          新增
        </el-button>
      </div>
    </el-card>

    <!-- 表格和分页区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="ID" prop="id" align="center" width="80" />
        <el-table-column label="角色名称" prop="name" align="center" />
        <el-table-column label="角色编码" prop="code" align="center" />
        <el-table-column label="描述" prop="description" align="center" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="{row}">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center" width="180" />
        <el-table-column label="操作" align="center" width="230">
          <template #default="{row}">
            <el-button type="primary" size="small" @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button v-if="row.status === 0" type="success" size="small" @click="handleModifyStatus(row,1)">
              启用
            </el-button>
            <el-button v-if="row.status === 1" type="warning" size="small" @click="handleModifyStatus(row,0)">
              禁用
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          v-show="total>0"
          v-model:current-page="listQuery.pageNum"
          v-model:page-size="listQuery.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="dataFormRef"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="temp.code" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="temp.description" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" class="filter-item" style="width: 100%">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="saveData">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted,nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createRole, updateRole, deleteRole, getRoleList, enableRole, disableRole } from '@/api/role'

const list = ref(null)
const total = ref(0)
const listLoading = ref(true)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dataFormRef = ref(null)

const listQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: ''
})

const temp = reactive({
  id: undefined,
  name: '',
  code: '',
  description: '',
  status: 1
})

const rules = reactive({
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})

const getList = () => {
  listLoading.value = true
  getRoleList(listQuery).then(response => {
    list.value = response.data.records
    total.value = response.data.total
    listLoading.value = false
  })
}

const handleFilter = () => {
  listQuery.pageNum = 1
  getList()
}

const resetTemp = () => {
  Object.assign(temp, {
    id: undefined,
    name: '',
    code: '',
    description: '',
    status: 1
  })
}

const handleCreate = () => {
  resetTemp()
  dialogTitle.value = '新增角色'
  dialogVisible.value = true
  nextTick(() => {
    dataFormRef.value?.clearValidate()
  })
}

const handleUpdate = (row) => {
  Object.assign(temp, row)
  dialogTitle.value = '编辑角色'
  dialogVisible.value = true
  nextTick(() => {
    dataFormRef.value?.clearValidate()
  })
}

const saveData = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      const data = { ...temp }
      if (temp.id) {
        updateRole(data).then(() => {
          dialogVisible.value = false
          ElMessage({
            type: 'success',
            message: '更新成功！'
          })
          getList()
        })
      } else {
        createRole(data).then(() => {
          dialogVisible.value = false
          ElMessage({
            type: 'success',
            message: '创建成功！'
          })
          getList()
        })
      }
    }
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该角色吗？', '提示', {
    type: 'warning'
  }).then(() => {
    deleteRole(row.id).then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功！'
      })
      getList()
    })
  })
}

const handleModifyStatus = async (row, status) => {
  const statusText = status === 1 ? '启用' : '禁用'
  try {
    if (status === 1) {
      await enableRole(row.id)
    } else {
      await disableRole(row.id)
    }
    row.status = status
    ElMessage.success(`${statusText}成功`)
  } catch (error) {
    console.error(`${statusText}失败:`, error)
  }
}

const handleSizeChange = (val) => {
  listQuery.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  listQuery.pageNum = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
}

.filter-item {
  margin-right: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}
</style> 